﻿using System;
using System.Collections.Generic;

using SBPweb.Forge.Contracts.Components;

using SBPweb.Communication.Shared.Library.Connections;

namespace SBPweb.Communication.Shared.Library.Contacts
{

    public abstract class ContactManagerBase : InitializableBase, IContactManager
    {

        #region Private fields

        #endregion

        #region Protected fields

        protected MessengerBase messenger;
        protected List<IContact> contacts;

        #endregion

        #region Constructor logic

        protected ContactManagerBase(MessengerBase messenger)
        {
            this.messenger = messenger;
            this.contacts = new List<IContact>();
        }

        #endregion

        #region Property accessors

        public virtual IContact Myself
        {
            get;
            protected set;
        }

        protected IMessenger Messenger
        {
            get
            {
                return messenger;
            }
        }

        public List<IContact> ContactList
        {
            get
            {
                return contacts;
            }
        }

        public IContactManagerConfiguration Configuration
        {
            get;
            protected set;
        }

        #endregion

        #region Events

        public event EventHandler ContactListRequested;

        public event EventHandler ContactListReceived;

        public event EventHandler<ContactPresenceStateBaseEventArgs> ContactPresenceChanged;

        #endregion

        #region Methods

        #region Configuration

        public void ApplyConfiguration(IContactManagerConfiguration configuration)
        {
            Configuration = configuration;
        }

        #endregion

        public abstract void GetContactList();

        protected void OnContactListReceiving(object sender, EventArgs e)
        {
            if (ContactListRequested != null)
            {
                ContactListRequested(sender, e);
            }
        }

        protected void OnContactListReceived(object sender, EventArgs e)
        {
            if (ContactListReceived != null)
            {
                ContactListReceived(sender, e);
            }
        }

        protected void OnContactPresenceChanged(object sender, ContactPresenceStateBaseEventArgs e)
        {
            if (ContactPresenceChanged != null)
            {
                ContactPresenceChanged(sender, e);
            }
        }

        protected IContact GetContactById(string id)
        {
            foreach (IContact contact in contacts)
            {
                if (contact.Id == id)
                {
                    return contact;
                }
            }
            return null;
        }

        #endregion

    }

}